/*
 * @lc app=leetcode.cn id=381 lang=cpp
 *
 * [381] O(1) 时间插入、删除和获取随机元素 - 允许重复
 */
class RandomizedCollection
{
public:
    /** Initialize your data structure here. */
    RandomizedCollection()
    {
    }

    /** Inserts a value to the collection. Returns true if the collection did not already contain the specified element. */
    bool insert(int val)
    {
        m[val].push_back(nums.size());
        nums.emplace_back(val, m[val].size() - 1);
        return m[val].size() == 1;
    }

    /** Removes a value from the collection. Returns true if the collection contained the specified element. */
    bool remove(int val)
    {
        if (!m.count(val))
        {
            return false;
        }
        int index = m[val].back();
        const auto &last = nums.back();
        m[last.first][last.second] = index;
        swap(nums.back(), nums[index]);
        nums.pop_back();
        m[val].pop_back();
        if (m[val].empty())
        {
            m.erase(val);
        }
        return true;
    }

    /** Get a random element from the collection. */
    int getRandom()
    {
        return nums[rand() % nums.size()].first;
    }

private:
    unordered_map<int, vector<int>> m;
    vector<pair<int, int>> nums;
};

/**
 * Your RandomizedCollection object will be instantiated and called as such:
 * RandomizedCollection* obj = new RandomizedCollection();
 * bool param_1 = obj->insert(val);
 * bool param_2 = obj->remove(val);
 * int param_3 = obj->getRandom();
 */
